package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_TTL;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryOrderByAsc(String sort) {
        //1.查询redis缓存
        List<String> cacheList = stringRedisTemplate.opsForList().range(RedisConstants.CACHE_SHOP_TYPE_KEY, 0, -1);

        List<ShopType> list = new ArrayList<>();
        //2.判断缓存是否存在
        if (cacheList != null && cacheList.size() > 0){
            //存在
            for (String s:cacheList
                 ) {
                ShopType shopType = JSONUtil.toBean(s, ShopType.class);
                list.add(shopType);
            }
            return Result.ok(list);
        }
        //4.不存在，查询数据库
        List<ShopType> list1 = list();
        //5.数据库不存在，返回错误
        if (list1 == null){
            //将空值写入redis
            //stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, "", RedisConstants.CACHE_NULL_TTL);
            return Result.fail("店铺不存在");
        }
        //6.存在，写入redis
        for (ShopType shopType:list1
             ) {
            stringRedisTemplate.opsForList().rightPush(RedisConstants.CACHE_SHOP_TYPE_KEY, JSONUtil.toJsonStr(shopType));
            stringRedisTemplate.expire(RedisConstants.CACHE_SHOP_TYPE_KEY, Duration.ofMinutes(CACHE_SHOP_TYPE_TTL));
        }
        //7.返回
        return Result.ok(list1);
    }
}
